package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/medivhzhan/weapp/payment"
	"yunshangxiaozhao/models"
	"yunshangxiaozhao/utils"
)

const (
	// AliPay 接口
	AliPartnerId  = "" // 合作者ID
	AliPartnerKey = "" // 合作者私钥
	AliReturnUrl  = "" // 同步返回地址
	AliNotifyUrl  = "" // 异步返回地址
	MyEmail       = "" // 卖家邮箱地址

	// WxPay 接口
	WxAppID      = "wx78ed10e1da8596d6"                        // APP ID
	WxMchID      = "1580144401"                                //商家号
	WxNotifyUrl  = "http://yunshangxiaozhao.com/v1/pay/notify" // 通知地址
	TestWxOpenId = "o_0Zt5Q68gbZDDMl4GTHABAwNxIc"              // 通知用户的 open id
	WxPayCode    = "Kj19ftPp0qRz3BYc4mWMLhlOXr8ZdNgC"          // 支付密钥
)

// Operations about pay
type PayController struct {
	beego.Controller
}

func (p *PayController) RetData(resp map[string]interface{}) {
	resp["code"] = 200
	p.Data["json"] = resp
	p.ServeJSON()
}

// @Title	CreatePay
// @Description	创建支付订单
// @Param Fee body int true "支付的价格(以分为单位)"
// @Success 200	{string} pay success
// @Failure 400 body is empty
// @router	/create [post]
func (p *PayController) CreatePay() {
	outTradeNo := utils.GenerateRandomOutTradeNo()
	resp := make(map[string]interface{})
	req := make(map[string]interface{})
	_ = json.Unmarshal(p.Ctx.Input.RequestBody, &req)
	totalFee := req["Fee"].(float64)

	userId := p.getUserIdFromSession()
	user, err := models.QueryUserById(userId)
	if user.OpenId == "" {
		p.Abort("WxNotBound")
	}

	form := payment.Order{
		AppID:      WxAppID,
		MchID:      WxMchID,
		TotalFee:   int(totalFee),
		NotifyURL:  WxNotifyUrl,
		OpenID:     user.OpenId,
		Body:       "云上校招-测试支付",
		OutTradeNo: outTradeNo,
	}

	res, err := form.Unify(WxPayCode)
	if err != nil {
		print(err.Error())
		return
	}

	params, err := payment.GetParams(res.AppID, WxPayCode, res.NonceStr, res.PrePayID)
	if err != nil {
		return
	}

	resp["params"] = params

	p.RetData(resp)
}

// @Title	NotifyUrl
// @Description	通知回调地址
// @Success 200	{string} pay success
// @Failure 400 body is empty
// @router	/notify [post]
func (p *PayController) Notify() {
	// TODO
}

func (p *PayController) getUserIdFromSession() int {
	id := p.GetSession("userId")
	if id == nil {
		p.Abort("UserNotLogin")
	}
	userId := id.(int)

	return userId
}
